/************************************************************************

								Heroes IV
					  Copyright 2000, The 3DO Company

	------------------------------------------------------------------
  						       cache_base.h

	$Header: /game/cache_base.h $

	$NoKeywords: $

 ************************************************************************/

#ifndef CACHE_BASE_H_INCLUDED
#define CACHE_BASE_H_INCLUDED

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include <list>
#include "data_lock.h"
#include "uncopyable.h"

class t_cache_base;

class t_cache_base_list : public std::list<t_cache_base*>
{
public:
	~t_cache_base_list();

	void lock();
	void unlock();
protected:
	t_data_lock m_lock;
};

inline void t_cache_base_list::lock()
{
	m_lock.lock();
}

inline void t_cache_base_list::unlock()
{
	m_lock.unlock();
}

// ------------------------------------------------------------
// base class for caching objects.  
// ------------------------------------------------------------
class t_cache_base : public t_uncopyable
{
public:
	friend class t_cache_base_list;

	t_cache_base();
	virtual ~t_cache_base();

	static void	check_memory();
	virtual int	get_size() = 0;

protected:
	void		 add_reference();
	void         add_to_free_list();
	int          get_ref_count() const;
	virtual void release_memory() = 0;
	void         remove_from_free_list();
	void		 remove_reference();
private:

	unsigned int				m_cahce_size;
	bool                        m_destroyed;
	t_cache_base_list::iterator m_position;
	int                         m_reference_count;

};

inline void t_cache_base::add_reference()
{
	if (m_reference_count == 0)
		remove_from_free_list();
	++m_reference_count;
}

inline int t_cache_base::get_ref_count() const
{
	return m_reference_count;
}

inline void t_cache_base::remove_reference()
{
	if ( !m_destroyed && --m_reference_count == 0 )
		add_to_free_list();
}

#endif

